"""
    Author:
    Date: 2019-07-30

    短网址管理类
"""

import requests

from django.conf import settings

from utils.log import Log

def make_short_link(url_long):
    """ 生成短链接(收费) """
    url = settings.ALI_SHORT_URL_API_URL

    session = requests

    app_code = settings.ALI_SHORT_URL_APPCODE
    headers = {'Authorization': f'APPCODE {app_code}'}
    payload = {
        'src': url_long,
    }

    Log.info(f'Make short link for {url_long} ......: url={url}')
    r = requests.post(url, data=payload, headers=headers)
    if r.status_code != 200:
        Log.info(f'Make short link for {url_long} failed: r.status_code = {r.status_code}')
        return None

    try:
        json_data = r.json()
    except Exception as e:
        Log.error(f'Make short link for {url_long} failed: ret={r}, exception={e}')
        return None

    Log.info(f'Make short link for {url_long}: ret={json_data}')

    if json_data['status'] != 200:
        Log.error(f'Make short link for {url_long} ...... FAILED!')

    url_short = json_data['msg']
    Log.info(f'Make short link for {url_long} ...... OK: {url_short}')
    return url_short


if __name__ == '__main__':
    print('ok')
